package com.whq.thrift.api.common.thriftclient;

import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;

import com.whq.thrift.api.common.thriftserver.ApiRequest;

public abstract class AbstractBaseCallback implements AsyncMethodCallback<Object> {
	// 处理服务返回的结果值
	public void onComplete(Object response) {
		if (response instanceof ApiRequest.AsyncClient.handleRequest_call) {
			ApiRequest.AsyncClient.handleRequest_call callResponse = (ApiRequest.AsyncClient.handleRequest_call) response;
			if (callResponse != null) {
				try {
					String result = callResponse.getResult();
					doResponse(result, null);
					return;
				} catch (TException e) {
					if (e instanceof TApplicationException 
		                    && ((TApplicationException) e).getType() ==   
		                                 TApplicationException.MISSING_RESULT) { 
						doResponse(null, null);
						return;
		            } 
				}
			}
		}

		if (response != null) {
			doResponse(response.toString(), null);	
		} else {
			doResponse(null, null);
		}
	}

	// 处理调用服务过程中出现的异常
	public void onError(Exception exception) {
		doResponse(null, exception);
	}

	public abstract void doResponse(String response, Exception exception);
}
